import { Button, Form, Input, Modal, Select, Upload } from 'antd';
import { UserData } from '@/types/sys';
import { addUser } from '@/api/sys';

const Dialog = (props: {
  open: boolean;
  title: string;
  setOpen: (open: boolean) => void;
  record: UserData | null;
  onSave: () => void;
}) => {
  const { open, title, setOpen, record, onSave } = props;
  const [form] = Form.useForm();

  useEffect(() => {
    if (open) {
      if (record) {
        // 修改
        form.setFieldsValue(record);
      } else {
        // 新增
        form.setFieldsValue({
          status: '1',
        });
      }
    }

    if (!open) {
      form.resetFields();
    }
  }, [record, open, form]);
  const onFinish = (values: UserData) => {
    console.log('Success:', values);
  };
  const onOk = () => {
    form.validateFields().then(async (values: UserData) => {
      console.log('Success:', values);
      const result = await addUser(values);
      console.log(result, 'result');
      onSave();
      setOpen(false);
    });
  };
  const onCancel = () => {
    setOpen(false);
  };
  return (
    <Modal title={title} open={open} onOk={onOk} onCancel={onCancel}>
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
      >
        <Form.Item
          label="账号"
          name="accessor"
          rules={[{ required: true, message: '请输入账号' }]}
        >
          <Input placeholder="请输入账号" />
        </Form.Item>

        <Form.Item
          label="昵称"
          name="nickname"
          rules={[{ required: true, message: '请输入昵称' }]}
        >
          <Input placeholder="请输入昵称" />
        </Form.Item>
        <Form.Item label="头像" name="avatar">
          <Upload>
            <Button>点击上传</Button>
          </Upload>
        </Form.Item>

        <Form.Item label="邮箱" name="email">
          <Input placeholder="请输入邮箱" />
        </Form.Item>
        <Form.Item label="手机号" name="phone">
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item label="状态" name="status">
          <Select placeholder="请选择状态">
            <Select.Option value="1">启用</Select.Option>
            <Select.Option value="0">禁用</Select.Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default Dialog;
